import React, { Component } from 'react';
import Container from '@icedesign/container';
import { Button, Dialog, Input, Message, Upload } from '@alifd/next';
import {
  FormBinderWrapper,
  FormBinder,
  FormError,
} from '@icedesign/form-binder';
import axios from "../../../../instances/request";
import { withRouter } from 'react-router-dom';
import FoundationSymbol from '@icedesign/foundation-symbol';
import { minHeight} from "../../../../conf/config";
import Cookies from 'universal-cookie';

const cookies = new Cookies();

@withRouter
export default class AccountPanel extends Component {
  static displayName = 'AccountPanel';

  constructor(props) {
    super(props);
    this.state = {
      open: false,
      user: {},
      value: {
        password: '',
        confirmPassword: '',
      },
      realFileName: '',
    };
  }

  handleOpenEditPanel = () => {
    this.setState({ open: true });
  };

  handleCloseEditPanel = () => {
    this.setState({ open: false });
  };

  formChange = (value) => {
    console.log('form', value);
    this.setState({
      value,
    })
  };

  changeMyInfo = () => {
    if(( this.state.value.password !== this.state.value.confirmPassword )) {
      Message.warning('前后密码需一致');
      return;
    }
    this.refs.form.validateAll((errors, values) => {
      if (errors) {
        console.log('errors', errors);
        return;
      }
      axios.post(`/staff/changeInfo`,{
        id: values.id,
        username: values.username,
        password: values.password,
        email: values.email,
        phone: values.phone,
        avatar: this.state.value.avatar[0] ? this.state.value.avatar[0].url : '',
        realFileName: this.state.realFileName,
      }).then((res) => {
        const { code, msg } = res.data;
        if(code !== 0) {
          Message.error(msg.error);
          this.props.history.push('/user/login');
          return;
        }
        Message.success('更改成功');
        this.setState({
          open: false
        });
        this.getAndSetUserData();
      })
    });
  };

  getAndSetUserData() {
    return axios
      .get(`/personalData`)
      .then((res) => {
        const { code, msg } = res.data;
        if(code !== 0) {
          // throw new Error(`code为${code}`);
          this.props.history.push('/user/login');  // 更改了密码
          return;
        }
        let { user } = msg;
        this.setState({
          user,
          value: {
            id: user.id,
            username: user.username,
            email: user.email,
            phone: user.phone,
            avatar: [{
              name: 'avatar',
              url: user.avatar,
            }]
          },
        });
      });
  }

  componentDidMount() {
    this.getAndSetUserData();
  }

  render() {
    return (
      <Container style={{ minHeight: `${minHeight}px`, padding: '0 0 20px 0' }}>
        <div style={{ height: '60px', background: '#EAEBEF' }}>
          <div style={
            {
              float: 'left',
              fontSize: '20px',
              fontWeight: 'bold',
              height: '60px',
              lineHeight: '60px',
              paddingLeft: '30px',
            }
          }>
            <FoundationSymbol type='shezhi' style={{ display: 'inline', verticalAlign: 'middle' }}/>
            <span>&nbsp;个人设置</span>
          </div>
          <div style={
            {
              height: '60px',
              lineHeight: '60px',
              float: 'right',
              marginRight: '20px'
            }
          }>
            <Button onClick={this.handleOpenEditPanel} type="primary">
              修改
            </Button>
          </div>
        </div>
        <div style={{ padding: '0 30px' }}>
          <div style={styles.infoRow}>
            <div style={styles.infoLabel}>账号头像</div>
            <div style={styles.infoDetail}>
              <img
                src={this.state.user.avatar || ''}
                style={{ width: 120 }}
                alt=""
              />
            </div>
          </div>
          <div style={styles.infoRow}>
            <div style={styles.infoLabel}>姓名</div>
            <div style={styles.infoDetail}>{this.state.user.username}</div>
          </div>
          <div style={styles.infoRow}>
            <div style={styles.infoLabel}>邮箱</div>
            <div style={styles.infoDetail}>{this.state.user.email}</div>
          </div>
          <div style={styles.infoRow}>
            <div style={styles.infoLabel}>手机号</div>
            <div style={styles.infoDetail}>{this.state.user.phone}</div>
          </div>
        </div>
        <Dialog
          visible={this.state.open}
          onOk={this.changeMyInfo}
          onClose={this.handleCloseEditPanel}
          onCancel={this.handleCloseEditPanel}
          title="修改账户信息"
        >
          <FormBinderWrapper
            ref="form"
            value={this.state.value}
            onChange={this.formChange}
          >
            <div>
              <div style={{
                ...styles.fromItem,
                display: 'none',
              }}>
                <div style={styles.formLabel}>用户id：</div>
                <FormBinder
                  name="id"
                >
                  <Input disabled />
                </FormBinder>
                <FormError name="id" />
              </div>
              <div style={styles.fromItem}>
                <div style={styles.formLabel}>头像：</div>
                <FormBinder
                  name="avatar"
                >
                  <Upload.Card
                    beforeUpload={(file, options) => {
                      return {
                        headers: {
                          token: cookies.get('token')
                        }
                      }
                    }}
                    listType="card"
                    accept='image/*'
                    action="/api/file/upload"
                    onSuccess={() => {
                      Message.success('文件上传成功');
                    }}
                    onError={(msg) => {
                      Message.error(msg.error);
                    }}
                    limit={1}
                    autoUpload={true}
                    formatter={(res, file) => {
                      // todo : this.setState写在这里就会崩溃 = - =，好像因为这里是render，而且被FormBinder包裹住，肯定是崩溃了
                      // this.setState({
                      //   realFileName: msg.filename,
                      // });
                      let { code, msg } = res;
                      return {
                        success: code === 0,
                        url: `/files/${msg.filename}`,
                      }
                    }}
                  />
                </FormBinder>
                <FormError name="avatar" />
              </div>
              <div style={styles.fromItem}>
                <div style={styles.formLabel}>姓名：</div>
                <FormBinder
                  name="username"
                  required
                  message="不能为空"
                  placeholder="请输入姓名"
                >
                  <Input style={{ width: 400 }} autoComplete="new-password" />
                </FormBinder>
                <FormError name="username" />
              </div>
              <div style={styles.fromItem}>
                <div style={styles.formLabel}>密码：</div>
                <FormBinder
                  name="password"
                  message="不能为空"
                >
                  <Input
                    style={{ width: 400 }}
                    htmlType="password"
                    placeholder="不输入则不更改密码"
                    autoComplete="new-password"
                  />
                </FormBinder>
                <FormError name="password" />
              </div>
              <div style={styles.fromItem}>
                <div style={styles.formLabel}>重复密码：</div>
                <FormBinder
                  name="confirmPassword"
                  message="不能为空"
                >
                  <Input
                    style={{ width: 400 }}
                    htmlType="password"
                    placeholder="不输入则不更改密码"
                    autoComplete="new-password"
                  />
                </FormBinder>
                <FormError name="confirmPassword" />
              </div>
              <div style={styles.fromItem}>
                <div style={styles.formLabel}>邮箱：</div>
                <FormBinder
                  name="email"
                  message='邮箱不合法'
                  pattern={new RegExp(/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/, 'gi')}
                >
                  <Input
                    style={{ width: 400 }}
                    autoComplete="new-password"
                    placeholder="请输入邮箱"
                  />
                </FormBinder>
                <FormError name="email" />
              </div>
              <div style={styles.fromItem}>
                <div style={styles.formLabel}>手机号：</div>
                <FormBinder
                  name="phone"
                  message='手机号不合法'
                  pattern={new RegExp(/^1([38]\d|5[0-35-9]|7[3678])\d{8}$/, 'gi')}
                >
                  <Input
                    style={{ width: 400 }}
                    autoComplete="new-password"
                    placeholder="请输入手机号"
                  />
                </FormBinder>
                <FormError name="phone" />
              </div>
            </div>
          </FormBinderWrapper>
        </Dialog>
      </Container>
    );
  }
}

const styles = {
  header: {
    display: 'flex',
    justifyContent: 'space-between',
  },
  title: {
    fontSize: 20,
    margin: 0,
    paddingBottom: 20,
  },
  infoRow: {
    padding: '16px 0',
    display: 'flex',
    borderBottom: '1px solid #f6f6f6',
  },
  infoLabel: {
    flex: '0 0 100px',
    color: '#999',
  },
  infoDetail: {},

  formLabel: {
    minWidth: '80px',
  },

  fromItem: {
    display: 'flex',
    alignItems: 'center',
    paddingBottom: 10,
  },
};
